package com.example.zhang;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class List_2Activity extends ListActivity implements Runnable,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
    private ArrayList<HashMap<String, String>> listItems;
    private static final String TAG ="a" ;
    String name;
    String data;
    String time = "123";
    Handler handler;
    SimpleAdapter listItemadapter;
    ArrayList<HashMap<String, String>> listItems1;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       // setContentView(R.layout.activity_list_2);
      //  ListView list3 = findViewById(R.id.list1);
        listItems = new ArrayList<HashMap<String, String>>();

        SharedPreferences sharedPreferences = getSharedPreferences("date", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        time = sharedPreferences.getString("time_save","123");
        Thread t = new Thread((Runnable) this);//开启后会启动子线程中的run方法.
        t.start();

        handler = new Handler(){
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what==1){
                    listItems1 = (ArrayList<HashMap<String, String>>)msg.obj;
                     listItemadapter = new SimpleAdapter(List_2Activity.this,
                            listItems1,
                            R.layout.list_item,
                            new String[]{"ItemTitle", "ItemDetail"},
                            new int[]{R.id.textView3, R.id.textView4});
                    setListAdapter(listItemadapter);
                    getListView().setEmptyView(findViewById(R.id.nodata));
                }
                super.handleMessage(msg);
            }
        };
        getListView().setOnItemClickListener(this);
        getListView().setOnItemLongClickListener(this);
        getListView().setEmptyView(findViewById(R.id.nodata));
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


        TextView title = (TextView) view.findViewById(R.id.textView3);
        TextView detail = (TextView) view.findViewById(R.id.textView4);
        String title2 = String.valueOf(title.getText());
        float detail2 =Float.parseFloat(String.valueOf(detail.getText()));
        Log.i(TAG, "onItemClick: title2="+title2);
        Log.i(TAG, "onItemClick: detail2="+detail2);
       // 打开新的页面
        Intent ratecalc = new Intent(this,rate_cal.class);
        ratecalc.putExtra("title",title2);
        ratecalc.putExtra("rate",detail2);
        startActivity(ratecalc);
    }
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position,long id){
        Log.i(TAG, "wuwuwu");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("请确认是否删除当前数据")
                .setNegativeButton("否",null)
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        listItems1.remove(position);
                        listItemadapter.notifyDataSetChanged();
                    }
                });
        builder.create().show();
        return true;
    }

    public void run() {

        Date date = new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");


            try {
                if (time.equals(format.format(date))) {
                    Log.i(TAG, "今天已经更新过了！！！" + "程序更新时间是：" + time);
                    DBManager dbManager = new DBManager((List_2Activity.this));
                    listItems=dbManager.listAll();
                }
                else {
                    Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
                    Element pro = doc.getElementsByTag("table").get(1);
                    Elements pros = pro.getElementsByTag("tr");

                    for (Element ppro : pros) {
                        Elements data1 = ppro.getElementsByTag("td");
                        if (data1.size() > 0 && !data1.get(1).text().isEmpty()) {
                            name = data1.get(0).text();
                            data = data1.get(1).text();
                            HashMap<String, String> map1 = new HashMap<String, String>();
                            map1.put("ItemTitle", name);
                            map1.put("ItemDetail", data);
                            listItems.add(map1);
                        }
                    }
                    DBManager dbManager = new DBManager(List_2Activity.this);
                    dbManager.deleteAll();
                    Log.i("db","删除所有记录");
                    dbManager.addAll(listItems);
                    Log.i("db","添加新记录集");
                    SharedPreferences sp = getSharedPreferences("date", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("time_save", format.format(date));
                    editor.apply();
                    Log.i(TAG, "完成每日更新" + format.format(date));
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        Message msg1 = handler.obtainMessage(1);
        msg1.obj =listItems;
        handler.sendMessage(msg1);
    }
}
